package com.hmz.backend.service.Impl.friend;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.entity.Friend;
import com.hmz.backend.entity.User;
import com.hmz.backend.mapper.FriendMapper;
import com.hmz.backend.mapper.UserMapper;
import com.hmz.backend.service.friend.GetUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class GetUserServiceImpl implements GetUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Override
    public JSONObject getUser(String username,int userId) {
        try {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(true, "user_name", username).ne("user_id", userId);
        List<User> userList = userMapper.selectList(queryWrapper); //模糊查询拿出所有符合要求的用户
        QueryWrapper<Friend> friendQueryWrapper = new QueryWrapper<>();
        friendQueryWrapper.eq("user_id", userId).or().eq("friend_id",userId);
        List<Friend> res = friendMapper.selectList(friendQueryWrapper); //拿出userId所有的朋友关系
        List<User> friends = new LinkedList<>(); //所有朋友的user对象
        for ( Friend friend: res) {
            int temp = friend.getUserId() == userId ? friend.getFriendId() : friend.getUserId();
            friends.add(userMapper.selectOne(new QueryWrapper<User>().eq("user_id",temp)));
        }
//        //有功夫改一下
//            for (User user : userList) {
//                boolean isFriend = false;
//                for (User friend:friends) {
//                    if (user.getUserName().equals(friend.getFriendname())) {
//                        isFriend = true;
//                        break;
//                    }
//                }
//                if (!isFriend) {
//                    list.add(user);
//                }
//            }
            //两个list做差集
            for (User friend:friends) if(userList.contains(friend)) userList.remove(friend);
            return new JSONObject().set("message", "查询成功").set("list", userList);
    }catch (Exception e) {
            return new JSONObject().set("message","查询失败！");

        }
    }
}
